import { useEffect, useRef, useState } from "react"
import { useParams, useHistory } from "react-router-dom"
import { Button, Descriptions, Spin, Space, Card, message, Modal } from 'antd'
import {
  queryDetail,
  queryTaskComments,
  createTaskComment,
  queryTaskForm,
  completeTask,
  completeTaskForm,
  saveTaskForm,
  claimTask
} from "../../apis/task"
import CommentList from "../../components/CommentList"
import { formatTime } from "../../utils/time"
import CommonModalForm from "../../components/common/CommonModalForm"
import useCURD from "../../hooks/useCURD"
import DetailHeader from "../../components/DetailHeader"
import SchemaForm from "../../components/FormDesigner/SchemaForm"
import { formatFormItems } from "../../utils/formItems"

const TaskCommentList = ({
  taskId,
  hideEdit
}) => {
  const {
    listData,
    loading,
    handleCreate,
    handleCancelForm,
    handleSubmit,
    formVisible,
    formTitle,
  } = useCURD({
    apis: {
      queryList: queryTaskComments,
      createOne: createTaskComment
    },
    moduleName: '评论',
    defaultQuery: {
      taskId: taskId,
      latestFirst: true
    },
    defaultSubmitValues: {
      taskId: taskId,
    }
  })

  const formItems = [
    {
      label: '评论内容',
      name: 'message'
    }
  ]

  return <Card
    title="评论"
    extra={
      !hideEdit && <a type="link" onClick={handleCreate}>添加评论</a>
    }
    size="small"
  >
    <CommonModalForm
      title={formTitle}
      visible={formVisible}
      onCancel={handleCancelForm}
      onSubmit={handleSubmit}
      formItems={formItems}
    ></CommonModalForm>
    <CommentList
      listData={listData}
    ></CommentList>
  </Card>
}

const WorkflowTaskDetail = () => {

  const { taskId } = useParams()
  const history = useHistory()
  const [loading, setLoading] = useState(false)

  const [detail, setDetail] = useState({})
  const formRef = useRef(null)
  const [formItems, setFormItems] = useState([])
  const [formId, setFormId] = useState(null)
  const [submitType, setSubmitType] = useState('')

  const doQueryDetail = async () => {
    if (!loading) {
      setLoading(true)
      try {
        const data = await queryDetail(taskId)
        setDetail(data)

        if (data.formKey) {
          const formRes = await queryTaskForm(taskId)
          setFormItems(formatFormItems(formRes.fields))
          let initValues = {}
          formRes.fields.forEach(el => {
            if (el.type === 'date' && el.value && el.value.split('-')[0].length !== 4) {
              initValues[el.id] = el.value.split('-').reverse().join('-')
            } else {
              initValues[el.id] = el.value
            }
          })
          formRef.current.setFieldsValue(initValues)
          setFormId(formRes.id)
        }
      } catch (error) {
        message.error('查询失败')
      }
      setLoading(false)
    }
  }
  useEffect(() => {
    if (taskId) {
      doQueryDetail()
    }
  }, [taskId])


  const handleSave = () => {
    setSubmitType('save')
    formRef.current.submit()
  }

  const doComplete = async () => {
    try {
      await completeTask({
        id: taskId
      })
      message.success('任务执行成功')
      setTimeout(() => {
        history.goBack()
      }, 1000)
    } catch (error) {
      message.error('任务执行失败')
    }
  }

  const handleComplete = () => {
    Modal.confirm({
      title: '确定要完成 ?',
      onOk: () => {
        if (formItems.length > 0) {
          setSubmitType('complete')
          formRef.current.submit()
        } else {
          doComplete()
        }
      }
    })
  }

  const handleSubmit = async (values) => {
    if (submitType === 'complete') {
      try {
        await completeTaskForm({
          taskId: taskId,
          formId: formId,
          values
        })
        message.success('任务执行成功')
        setTimeout(() => {
          history.goBack()
        }, 1000)
      } catch (error) {
        message.error('任务执行失败')
      }
    } else if (submitType === 'save') {
      try {
        await saveTaskForm({
          taskId: taskId,
          formId: formId,
          values
        })
        message.success('保存成功')
      } catch (error) {
        message.error('保存失败')
      }
    }
  }

  const handleClaimTask = () => {
    Modal.confirm({
      title: '确定要认领？',
      onOk: async () => {
        try {
          await claimTask(taskId)
          message.success('任务认领成功')
          doQueryDetail()
        } catch (error) {
          message.error('任务认领失败')
        }
      }
    })
  }

  const renderBtns = () => {
    if (detail.endDate) {
      return null
    } else {
      if (detail.assignee) {
        return <Space>
          {
            !!formId && <Button onClick={handleSave}>保存</Button>
          }
          <Button type="primary" onClick={handleComplete}>完成</Button>
        </Space>
      } else {
        return <Button type="primary" onClick={handleClaimTask}>认领</Button>
      }
    }
  }

  return <Spin spinning={loading} wrapperClassName="page-wrap">

    <DetailHeader
      title={<b style={{ fontSize: 16 }}>{detail.name}</b>}
      extra={renderBtns()}
    ></DetailHeader>
    <div className="page-body" style={{ display: "flex" }}>
      <div style={{ height: '100%', flex: 1, marginRight: 20, overflow: 'auto' }}>
        <Card title="任务信息" size="small">
          <Descriptions bordered size="small">
            <Descriptions.Item label="被分配人">
              {detail.assignee ? detail.assignee.fullName : '暂无'}
            </Descriptions.Item>
            <Descriptions.Item label="流程">
              {detail.processDefinitionName}
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              {formatTime(detail.created)}
            </Descriptions.Item>
            {
              detail.dueDate &&
              <Descriptions.Item label="到期时间">
                {formatTime(detail.dueDate)}
              </Descriptions.Item>
            }
            {
              detail.endDate &&
              <Descriptions.Item label="完成时间">
                {formatTime(detail.endDate)}
              </Descriptions.Item>
            }
          </Descriptions>
          {
            formItems.length > 0 &&
            <Card title="任务表单" size="small" style={{ marginTop: 20 }}>
              <div style={{ maxWidth: 600, paddingTop: 20 }}>
                <SchemaForm
                  ref={formRef}
                  formItems={formItems}
                  onSubmit={handleSubmit}
                ></SchemaForm>
              </div>
            </Card>
          }
        </Card>
      </div>
      <div style={{ height: '100%', width: 300, overflow: 'auto' }}>
        <TaskCommentList
          taskId={taskId}
          hideEdit={!!detail.endDate}
        ></TaskCommentList>
      </div>
    </div>
  </Spin>
}

export default WorkflowTaskDetail